package com.bdqn.t382.service;

import com.bdqn.t382.entity.SysUser;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.AbstractController;

import java.util.Map;

@Controller
@RequestMapping("/dev")
public class HelloController {
    private static final Logger LOGGER =
            LoggerFactory.getLogger(HelloController.class);

    // 定义入参参数，required 默认为 true 表示必填，设置为 false，则非必填
    @RequestMapping("/hello")
    protected ModelAndView hello(@RequestParam(name = "realName", required = false)
                                 String name) throws Exception {
        LOGGER.info("你好{}，欢迎学习 SpringMVC!", name);
        ModelAndView modelAndView = new ModelAndView();
        // 添加对象到 Model 模型数据中，类似于 request.setAttribute()方法
        modelAndView.addObject("realName", name);
        // 设置逻辑视图名
        modelAndView.setViewName("hello");
        return modelAndView;
    }

    // 一个控制器类中可以定义多个控制器方法
    @RequestMapping("/welcome")
    protected String welcome(HttpServletRequest request) throws Exception {
        LOGGER.info("进入控制器 welcome 方法，请求路径为:{}",
                request.getRequestURI());
        return "hello";
    }

    @RequestMapping("/model")
    public String model(Model model,
                        @RequestParam(name = "realName", required = false)
                        String name) throws Exception {
        LOGGER.info("你好{}，在参数注入 Model 对象也可以出参!", name);
        // 使用 model 对象添加数据
        model.addAttribute("realName", name);
        // 创建 SysUser 对象，并存入 model 对象
        SysUser sysUser = new SysUser();
        sysUser.setRealName(name);
        model.addAttribute("sysUser", sysUser);
        return "hello";
    }

    @RequestMapping("/map")
    public String model(Map map,
                        @RequestParam(name = "realName", required = false)
                        String name) throws Exception {
        LOGGER.info("你好{}，在参数注入 Map 对象也可以出参!", name);
        // 使用 model 对象添加数据
        map.put("realName", name);
        // 创建 SysUser 对象，并存入 model 对象
        SysUser sysUser = new SysUser();
        sysUser.setRealName(name);
        map.put("sysUser", sysUser);
        return "hello";
    }
}
